<template>
  <div class="swarmsSOP">
    <div>
      <van-sticky>
        <div style="background: #fafafa;">
          <div class="swarmsSOP_message">
            <div class="swarmsSOP_message_top">
              <div class="swarmsSOP_message_top_left">
                <div class="swarmsSOP_message_top_left_userImg">
                  <img v-if="form.avatar" :src="form.avatar" alt="" />
                </div>
                <div class="swarmsSOP_message_top_left_info">
                  <div>
                    {{ form.customerName
                    }}<span :style="{ color: form.customerType === 1 ? '#4bde03' : '#f9a90b' }">
                      {{ { 1: '@微信', 2: form.corpName ? '@' + form.corpName : '@企业微信' }[form.customerType] }}
                    </span>
                  </div>
                  <div>
                    <img v-if="form.gender === 1" src="../../../../assets/man.png" />
                    <img v-else-if="form.gender === 2" src="../../../../assets/woman.png" />
                  </div>
                </div>
              </div>
              <div class="swarmsSOP_message_top_right">
                {{ trackStateFn(form.trackState) }}
              </div>
            </div>
          </div>
          <div class="swarmsSOP_tabBar">
            <div @click="setChange(0)" :class="tabBar == 0 ? 'swarmsSOP_tabBar_li1' : 'swarmsSOP_tabBar_li'">
              待推送
            </div>
            <div @click="setChange(1)" :class="tabBar == 1 ? 'swarmsSOP_tabBar_li1' : 'swarmsSOP_tabBar_li'">
              已推送
            </div>
          </div>
        </div>
      </van-sticky>

      <div class="swarmsSOP_box" style="display: flex; flex-direction: column; align-items: center;">
        <NoData v-if="!dataList.length"></NoData>
        <div v-else v-for="(item, index) in dataList" :key="index" class="swarmsSOP_content">
          <div
            :class="{
              swarmsSOP_content_top1: item.type === 1,
              swarmsSOP_content_top2: item.type === 2,
              swarmsSOP_content_top3: item.type === 3
            }"
          >
            <div style="margin-bottom: 12px;" class="swarmsSOP_content_top_text">{{ item.sopName }}</div>
            <div v-if="item.type === 1 && tabBar === 0" class="swarmsSOP_content_top_text">
              距推送结束剩余{{ item.time }}
            </div>
            <div v-if="item.type === 2 && tabBar === 0" class="swarmsSOP_content_top_text">
              距推送时间已过{{ item.time }}
            </div>
            <div v-if="item.type === 3 && tabBar === 0" class="swarmsSOP_content_top_text">未到推送时间</div>
          </div>
          <div @click="item.open = !item.open" class="swarmsSOP_content_title">
            <div>
              SOP内容
            </div>
            <div class="swarmsSOP_message_content_box_li_right">
              <img v-if="!item.open" src="@/assets/Applications/topj3.png" alt="" />
              <img style="transform: rotate(180deg);" v-if="item.open" src="@/assets/Applications/topj3.png" alt="" />
            </div>
          </div>
          <div class="swarmsSOP_content_li" v-if="item.open">
            <template v-for="(unit, key) in item.list">
              <div class="unit" :key="key">
                <ShowSendInfo :key="key + 111" :obj="unit.weQrAttachments"></ShowSendInfo>
                <div class="operation" :key="key" v-if="tabBar === 0">
                  <span style="color: #00bf2f;" v-if="item.type !== 3 && unit.executeState === 1">已发送</span>
                  <span style="color: #ed4014;" v-if="item.type !== 3 && unit.executeState === 0">待发送</span>
                  <span v-if="item.type === 3">未到推送时间</span>
                  <van-button
                    type="info"
                    v-if="unit.executeState === 0 && item.type !== 3"
                    @click="send(unit.weQrAttachments, unit.executeTargetAttachId)"
                  >
                    发送
                  </van-button>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <Loading :isLoad="isLoad" />
  </div>
</template>

<script>
  import NoData from '@/components/NoData.vue'
  import Loading from '@/components/Loading.vue'
  import { getCustomerSopContent, getSuccess } from '@/api/sop'
  import { compareTime } from '@/utils/index.js'
  import ShowSendInfo from '@/components/ShowSendInfo'
  import { getMaterialMediaId } from '@/api/chat'
  export default {
    name: 'customer-sop',
    components: {
      ShowSendInfo,
      Loading,
      NoData
    },
    data() {
      return {
        stateActions: [
          { name: '待跟进', color: '', type: 1 },
          { name: '跟进中', color: 'warning', type: 2 },
          { name: '已成交', color: 'success', type: 3 },
          { name: '无意向', color: 'info', type: 4 },
          { name: '已流失', color: 'danger', type: 5 }
        ],
        isLoad: false,
        externalUserId: '',
        tabBar: 0,
        form: {
          avatar: '',
          customerName: '',
          customerType: null,
          externalUserid: '',
          gender: null,
          trackState: null,
          weCustomerSops: []
        },
        dataList: []
      }
    },
    props: {
      userId: {
        type: String,
        default: ''
      }
    },
    watch: {
      userId: {
        immediate: true,
        handler(val) {
          if (val) {
            this.externalUserId = val
            this.getData(0)
          }
        }
      }
    },
    created() {},
    methods: {
      filType(file) {
        let filecontent = JSON.parse(JSON.stringify(file))
        filecontent = filecontent.split('.')
        let type = filecontent[filecontent.length - 1]
        if (type === 'pdf') {
          return window.lwConfig.DEFAULT_H5_PDF
        } else if (['doc', 'docx'].includes(type)) {
          return window.lwConfig.DEFAULT_H5_WORDE
        } else if (['ppt', 'pptx', 'pps', 'pptsx'].includes(type)) {
          return window.lwConfig.DEFAULT_H5_PPT
        } else {
          return window.lwConfig.DEFAULT_H5_PIC
        }
      },
      trackStateFn(state) {
        let str = ''
        this.stateActions.forEach((dd) => {
          if (dd.type === state) {
            str = dd.name
          }
        })
        return str
      },
      setChange(type) {
        this.tabBar = type
        this.getData(type)
      },
      send(data, id) {
        this.$toast.loading({
          message: '正在发送...',
          duration: 0,
          forbidClick: true
        })
        let _this = this
        wx.invoke('getContext', {}, async function (res) {
          if (res.err_msg == 'getContext:ok') {
            let mes = {}
            try {
              switch (data.msgType) {
                case 'text':
                default:
                  mes.text = {
                    content: data.content //文本内容
                  }
                  mes.msgtype = data.msgType
                  break
                case 'image':
                  let dataMediaId = {
                    url: data.picUrl,
                    type: data.msgType,
                    name: data.materialName
                  }
                  try {
                    let resMaterialId = await getMaterialMediaId(dataMediaId)
                    if (!resMaterialId.data) {
                      _this.$toast('获取素材id失败')
                      return
                    }
                    _this.$set(mes, data.msgType, {
                      mediaid: resMaterialId.data.mediaId //
                    })
                    mes.msgtype = data.msgType
                  } catch (error) {
                    _this.$toast.clear()
                    return
                  }
                  break
                case 'video':
                case 'file':
                  let linkUrl =
                    window.document.location.origin +
                    window.lwConfig.BASE_URL +
                    '#/metrialDetail?mediaType=' +
                    data.msgType +
                    '&materialUrl=' +
                    data.linkUrl
                  mes.news = {
                    link: linkUrl, //H5消息页面url 必填
                    title: data.title ? data.title : '', //H5消息标题
                    desc: data.description ? data.description : '', //H5消息摘要
                    imgUrl: _this.filType(data.linkUrl)
                  }
                  mes.msgtype = 'news'
                  break
                case 'link':
                  mes.news = {
                    link: data.linkUrl, //H5消息页面url 必填
                    title: data.title ? data.title : '', //H5消息标题
                    desc: data.description ? data.description : '', //H5消息摘要
                    imgUrl: window.lwConfig.DEFAULT_H5_PIC //H5消息封面图片URL
                  }
                  mes.msgtype = 'news'
                  break
                case 'miniprogram':
                  mes.miniprogram = {
                    appid: data.appId, //小程序的appid，企业已关联的任一个小程序
                    title: data.title, //小程序消息的title
                    imgUrl: data.picUrl, //小程序消息的封面图。必须带http或者https协议头，否则报错 $apiName$:fail invalid imgUrl
                    page: data.linkUrl //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
                  }
                  mes.msgtype = data.msgType
                  break
              }
            } catch (err) {
              _this.$dialog({ message: 'err' + JSON.stringify(err) })
            }
            wx.invoke('sendChatMessage', mes, function (resSend) {
              if (resSend.err_msg == 'sendChatMessage:ok') {
                //发送成功 sdk会自动弹出成功提示，无需再加
                _this.setSuccessFn(id)
              }
              if ('sendChatMessage:cancel,sendChatMessage:ok'.indexOf(resSend.err_msg) < 0) {
                //错误处理
                _this.$dialog({ message: '发送失败：' + JSON.stringify(resSend) })
              }
            })
            _this.$toast.clear()
          } else {
            _this.$toast.clear()
            //错误处理
            _this.$dialog({ message: '进入失败：' + JSON.stringify(res) })
          }
        })
      },
      setSuccessFn(targetId) {
        getSuccess(targetId).then((res) => {
          this.getData(0)
        })
      },
      getData(state) {
        this.isLoad = true
        getCustomerSopContent({ targetId: this.externalUserId, executeSubState: state }).then((res) => {
          if (res.code === 200) {
            this.form = res.data
            let arr = this.form.weCustomerSops
            if (arr && arr.length) {
              this.resetData(arr)
            } else {
              this.dataList = []
            }
          }
          this.isLoad = false
        })
      },
      resetData(array) {
        this.dataList = []
        array.forEach((dd) => {
          let data = this.sorted(dd.weCustomerSopContents, 'pushStartTime')
          let val = Object.keys(data)
          let result = []
          val.forEach((ff) => {
            result.push({
              sopBaseId: dd.sopBaseId,
              sopName: dd.sopName,
              open: false,
              list: data[ff]
            })
          })
          this.dataList.push(...result)
        })
        this.setStateData()
      },
      setStateData() {
        this.dataList.forEach((dd) => {
          let str = compareTime(dd.list[0].pushStartTime, dd.list[0].pushEndTime)
          if (str === 'before') {
            dd.type = 3 // 未到推送时间
          } else if (str === 'after') {
            dd.type = 2 // 已过推送时间
            dd.time = this.computeTime(dd.list[0].pushEndTime)
          } else {
            dd.time = this.computeTime(dd.list[0].pushEndTime)
            dd.type = 1 // 已到推送时间
          }
        })
      },
      computeTime(t2) {
        let aftert2 = new Date(t2.replace(/-/g, '/')) //转换
        let data = new Date() //获取当前时间
        let times = aftert2.getTime() - data.getTime() //时间差的毫秒数
        // let days = parseInt(times / (24 * 1000 * 3600)) //计算相差的天数
        let leave = times % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        let h = Math.abs(parseInt(leave / (3600 * 1000))) //计算小时数
        //计算分钟数
        let h_leave = leave % (3600 * 1000)
        let min = Math.abs(parseInt(h_leave / (60 * 1000)))
        //计算秒数
        let min_leave = h_leave % (60 * 1000)
        let sec = Math.abs(parseInt(min_leave / 1000))
        return `${h}时${min}分${sec}左右`
      },
      sorted(array, key) {
        let groups = {}
        array.forEach(function (item) {
          let value = item[key]
          groups[value] = groups[value] || []
          groups[value].push(item)
        })
        return groups
      }
    }
  }
</script>

<style lang="less" scoped>
  .unit {
    background: #ffffff;
    box-shadow: 0px 2px 6px 0px rgba(60, 136, 240, 0.1);
    border: 1px solid #e1edfc;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
  }
  .operation {
    display: flex;
    margin-top: 5px;
    align-items: center;
    justify-content: space-between;
  }
  .swarmsSOP {
    width: 100%;
    // height: 100vh;
    background: #fafafa;
    // position: relative;

    .swarmsSOP_box {
      padding: 10px;
    }

    .swarmsSOP_message {
      border-radius: 3px;
      display: flex;
      flex-direction: column;
      font-weight: 500;
      background: #fff;
      min-height: 25px;
      padding: 9px 10px;
      color: #222121;
      width: 100%;

      .swarmsSOP_message_top {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .swarmsSOP_message_top_left {
          display: flex;

          .swarmsSOP_message_top_left_userImg {
            width: 50px;
            height: 50px;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .swarmsSOP_message_top_left_info {
            padding-top: 2px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 10px;

            img {
              width: 16px;
              height: 16px;
            }
          }
        }

        .swarmsSOP_message_top_right {
          padding: 6px 15px;
          background-color: #2c8cf0;
          color: #fff;
          border-radius: 5px;
        }
      }
    }
    .swarmsSOP_tabBar {
      margin-top: 10px;
      display: flex;
      border-radius: 10px 10px 0 0;
      background-color: #fff;
      // border: 1px solid #7f7f7f;
      overflow: hidden;
      .swarmsSOP_tabBar_li {
        background-color: #fff;
        color: #7f7f7f;
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
        height: 40px;
      }
      .swarmsSOP_tabBar_li1 {
        background-color: #7f7f7f;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
        height: 40px;
      }
    }
  }
  .swarmsSOP_content {
    overflow: hidden;
    border-radius: 10px;
    margin-top: 20px;
    width: 100%;
    background-color: #fff;
    .swarmsSOP_content_top1 {
      background-color: #90f8e3;
      padding: 15px 10px;
      .swarmsSOP_content_top_text {
        color: #1abc9c;
      }
    }
    .swarmsSOP_content_top2 {
      background-color: #fdb2a0;
      padding: 15px 10px;
      .swarmsSOP_content_top_text {
        color: #ed4014;
      }
    }
    .swarmsSOP_content_top3 {
      background-color: #b5b1b1;
      padding: 15px 10px;
      .swarmsSOP_content_top_text {
        color: #7f7f7f;
      }
    }
  }
  .swarmsSOP_content_title {
    padding: 10px 10px;
    display: flex;
    justify-content: space-between;
  }
  .swarmsSOP_message_content_box_li_right {
    width: 16px;
    height: 16px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .swarmsSOP_content_li {
    background-color: #f6faff;
    padding: 10px;
    .swarmsSOP_content_li_text {
      background-color: #fff;
    }
  }
</style>
